﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using log4net;
using mshtml;
using Nissen_Common;
using Nissen_Model;
using Nissen_Resources;
using PosHacker;
using Utility_Log;

namespace Nissen_Marking.Forms
{
	public partial class FormInconsistentMark : Form
	{
		public Form MainForm { get; set; }
		public POSHacker vPOSHacker;

		private string MainLink { get; set; }
		private  IList<string> UnDoData { get; set; }
		private string subjectCourseTestId { get; set; }
		
		public FormInconsistentMark(string vLink)
		{

			InitializeComponent();

			this.webBrowser1.Url = new Uri(vLink);

			MainLink = vLink;

		
		}


		private void FormInconsistentMark_Load(object sender, EventArgs e)
		{
			//this.webBrowser1.Document.DomDocument = new mshtml.HTMLDocument(); //new Uri(vLink);
			this.btnNG.Enabled = false;
			this.btnMarkConfirmed.Enabled = false;
		}

		private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
		{
			if (e.Url.ToString() != webBrowser1.Url.ToString())
				return;

			
			IHTMLDocument2 doc = (IHTMLDocument2)webBrowser1.Document.DomDocument;

			doc.parentWindow.execScript(@"function popupModalWindow(configured)
											{
												if (configured == true) {
														url = '/MarkingSystemWeb/preparePcMarking.do';
														var now = new Date().getTime();
														var args = new Object();
														args.window = window;
														//var ret = window.showModalDialog(url+'?time='+now,args,'dialogWidth=' + screen.width + 'px; dialogHeight=' + screen.height + 'px; status=no; resizable=yes; help=no; maximize=yes;');
														//document.forms['mismatchListForm'].submit();
														window.location.href = url;
												}
											}", "javascript");

			if (webBrowser1.Url.LocalPath == "/MarkingSystemWeb/preparePcMarking.do" || webBrowser1.Url.LocalPath == "/MarkingSystemWeb/markConfig.do" || webBrowser1.Url.LocalPath == "/MarkingSystemWeb/confirmPcMark.do")
			{
				this.PageControl();
				this.btnMarkConfirmed.Visible = true;
				this.btnNG.Visible = true;

				this.btnMarkConfirmed.Enabled = true;
				this.btnNG.Enabled = true;
				UnDoData = GetLoadData();

				if(webBrowser1.Document.GetElementById("subjectCourseTestId")!=null)
				{
					var tempSubjectCourseTestId= webBrowser1.Document.GetElementById("subjectCourseTestId").GetAttribute("value");
					if(!string.IsNullOrEmpty(tempSubjectCourseTestId))
					{
						this.subjectCourseTestId = tempSubjectCourseTestId;
					}
				}
			}
			else
			{
				this.btnMarkConfirmed.Visible = false;
				this.btnNG.Visible = false;
			}

		}
		/// <summary>
		/// 画面控制
		/// </summary>
		private void PageControl()
		{

			HTMLDocument mainFrmhtmlDocument = (HTMLDocument)webBrowser1.Document.Window.Frames["mainFrm"].Document.DomDocument;

			var btnBackToMenu = (HTMLButtonElement)mainFrmhtmlDocument.getElementById("backToMenu");

			if (btnBackToMenu != null)
			{
				btnBackToMenu.outerHTML = this.DivHidden(btnBackToMenu.outerHTML);
			}

			HTMLDocument answerSheetFrmHtmlDocument = (HTMLDocument)webBrowser1.Document.Window.Frames["answerSheetFrm"].Document.DomDocument;

			var btnOk = (HTMLButtonElement)answerSheetFrmHtmlDocument.getElementById("ok");

			var btnNg = (HTMLButtonElement)answerSheetFrmHtmlDocument.getElementById("ng");

			if (btnOk != null)
			{
				btnOk.outerHTML = this.DivHidden(btnOk.outerHTML);
			}
			if (btnNg != null)
			{
				btnNg.outerHTML = this.DivHidden(btnNg.outerHTML);
			}


			//IHTMLDocument2 doc = (IHTMLDocument2)webBrowser1.Document.DomDocument;

			//foreach (IHTMLElement LV0 in doc.all)
			//{
			//    if (LV0.tagName.ToUpper() == "FRAME")
			//    {
			//        //返回按钮隐藏
			//        IHTMLFrameBase2 LV0_FRAME = (IHTMLFrameBase2)LV0;
			//        if (LV0_FRAME.contentWindow.name == "mainFrm")
			//        {

			//            HTMLDocument doc1 = (HTMLDocument)LV0_FRAME.contentWindow.document;
			//            HTMLButtonElement button = (HTMLButtonElement)doc1.getElementById("backToMenu");
			//            if (button != null)
			//            {
			//                button.outerHTML = this.DivHidden(button.outerHTML);
			//            }
			//            //foreach (IHTMLElement LV2 in LV0_FRAME.contentWindow.document.all)
			//            //{
			//            //    HTMLDocument doc1 = (HTMLDocument)LV2.document;
			//            //    HTMLButtonElement button = (HTMLButtonElement)doc1.getElementById("backToMenu");
			//            //    if (button != null)
			//            //    {
			//            //        button.outerHTML = this.DivHidden(button.outerHTML);
			//            //    }
			//            //}
			//        }
			//        //提交按钮隐藏
			//        if (LV0_FRAME.contentWindow.name == "answerSheetFrm")
			//        {
			//            HTMLDocument doc1 = (HTMLDocument)LV0_FRAME.contentWindow.document;
			//            HTMLButtonElement okButton = (HTMLButtonElement)doc1.getElementById("ok");
			//            if (okButton != null)
			//            {
			//                okButton.outerHTML = this.DivHidden(okButton.outerHTML);
			//            }
			//            HTMLButtonElement ngButton = (HTMLButtonElement)doc1.getElementById("ng");
			//            if (ngButton != null)
			//            {
			//                ngButton.outerHTML = this.DivHidden(ngButton.outerHTML);
			//            }


						//foreach (IHTMLElement LV2 in LV0_FRAME.contentWindow.document.all)
						//{

						//    HTMLDocument doc1 = (HTMLDocument)LV2.document;
						//    HTMLButtonElement okButton = (HTMLButtonElement)doc1.getElementById("ok");
						//    if (okButton != null)
						//    {
						//        okButton.outerHTML = this.DivHidden(okButton.outerHTML);
						//    }
						//    HTMLButtonElement ngButton = (HTMLButtonElement)doc1.getElementById("ng");
						//    if (ngButton != null)
						//    {
						//        ngButton.outerHTML = this.DivHidden(ngButton.outerHTML);
						//    }

						//}
			//        }
			//    }

			//}
		}
		/// <summary>
		/// 隐藏控件
		/// </summary>
		/// <param name="strOutHtml"></param>
		/// <returns></returns>
		private string DivHidden(string strOutHtml)
		{

			return "<div style=\"visibility:hidden\">" + strOutHtml + "</div>";
		}
		private void btnBack_Click(object sender, EventArgs e)
		{
			var tempLink = vPOSHacker.GetInconsistentMarkActionLink();
			this.webBrowser1.Url = new Uri(tempLink);
		}

		private void FormInconsistentMark_FormClosed(object sender, FormClosedEventArgs e)
		{
			this.MainForm.Show();
		}

		private void btnMarkConfirmed_Click(object sender, EventArgs e)
		{
			try
			{
				if (this.btnMarkConfirmed.Enabled == false)
				{
					return;
				}
				this.btnNG.Enabled = false;
				this.btnMarkConfirmed.Enabled = false;

				submitForm(true);

			}
			catch (Exception ex)
			{
				MessageBox.Show(ResourceCommon.GetResource("SubmitFail")); 
				Log4netManager.Instance.Logs.Error("error", ex);
			}
			
		}

		private void btnNG_Click(object sender, EventArgs e)
		{
			try
			{
				if (this.btnNG.Enabled == false)
				{
					return;
				}
				this.btnNG.Enabled = false;
				this.btnMarkConfirmed.Enabled = false;

				submitForm(false);
			}
			catch (Exception ex) 
			{
				MessageBox.Show(ResourceCommon.GetResource("SubmitFail"));
				Log4netManager.Instance.Logs.Error("error", ex);
			}
			
		}

		/// <summary>
		/// 获得检证数据
		/// </summary>
		/// <returns></returns>
		private List<string> GetLoadData()
		{
			List<string > unDoData = new List<string>();

			HtmlElementCollection inputs = webBrowser1.Document.GetElementsByTagName("input");

			if (webBrowser1.Document.GetElementById("regNo") != null)
			{
				foreach (HtmlElement input in inputs)
				{

					var inputName = input.GetAttribute("name");
					Regex rg = new Regex(@"^markMap");
					Match mc = rg.Match(inputName);
					if (mc.Success)
					{
						var inputValue = input.GetAttribute("value");
						if (inputValue != "9")
						{
							continue;
						}
						var questionNo = "";
						string parrentStr = @"markMap\((\d+)\)";
						Match ma = Regex.Match(inputName, parrentStr, RegexOptions.IgnoreCase);
						if (ma.Success)
						{
							questionNo = ma.Groups[1].ToString();
							//题号
							unDoData.Add(questionNo);
						}

					}

				}

			}
			
			return unDoData;

		}


		/// <summary>
		/// 获得提交数据
		/// </summary>
		/// <returns></returns>
		private List<RecordData> GetSubmitData(string submitFlag)
		{
			List<RecordData> recordDatas = new List<RecordData>();

			HtmlElementCollection inputs = webBrowser1.Document.GetElementsByTagName("input");

			var regNo = webBrowser1.Document.GetElementById("regNo").GetAttribute("value");

			foreach (HtmlElement input in inputs)
			{
				var inputName = input.GetAttribute("name");
				Regex rg = new Regex(@"^markMap");
				Match mc = rg.Match(inputName);
				if (mc.Success)
				{
					var questionNo = "";
					string parrentStr = @"markMap\((\d+)\)";
					Match ma = Regex.Match(inputName, parrentStr, RegexOptions.IgnoreCase);
					if (ma.Success)
					{
						//题号
						questionNo = ma.Groups[1].ToString();

						if(!UnDoData.Contains(questionNo))
						{
							 continue;	
						}
					}
					RecordData recordData = new RecordData();

					var strQuestionNo = regNo
								  + "_"
								  + subjectCourseTestId
								  + "_"
								  + questionNo
                                  + "_B";

					recordData.QuestionNo = strQuestionNo;
					if (submitFlag == "ok")
					{
						recordData.QuestionResult = input.GetAttribute("value");
					}
					else if (submitFlag == "ng")
					{
						recordData.QuestionResult = "5";
					}
					recordData.WorkerNo = Nissen_Common.ContextManager.Instance.CurrentUser.LoginSSO;
					recordData.NissenSSO = Nissen_Common.ContextManager.Instance.CurrentUser.NissenSSO.NissenSSOCode;
					recordData.FirstWorkDate = DateTime.Now;
					recordData.EndWorkDate = DateTime.Now;

					recordData.MachineCode = "";
					recordDatas.Add(recordData);
				}

			}
			return recordDatas;

		}

		private void submitForm(bool result)
		{
			if (result == true)
			{
				bool existUnmarkedItem =
					(bool)webBrowser1.Document.Window.Frames["answerSheetFrm"].Document.InvokeScript("existUnmarkedItem");

				if (existUnmarkedItem == true)
				{
					//There are some unmarked question. Save this ?
					if (
						MessageBox.Show(ResourceCommon.GetResource("SubmitPCMarkingConfirm"), "", MessageBoxButtons.OKCancel,
										MessageBoxIcon.Question) == DialogResult.Cancel)
					{
						return;
					}
				}
				LogMarkInfo("ok");

			}
			else
			{
				//Is it OK to change status to "to be fixed". \nIf OK, please go ahead and call administraor.
				if (
					MessageBox.Show(ResourceCommon.GetResource("AbnormalDataConfirm"), "", MessageBoxButtons.OKCancel,
									MessageBoxIcon.Question) == DialogResult.Cancel)
				{
					return;
				}
				LogMarkInfo("ng");
				webBrowser1.Document.GetElementById("isAbnormal").SetAttribute("value", "true");

			}
			webBrowser1.Document.GetElementById("isSkipped").SetAttribute("value", "false");
			webBrowser1.Document.GetElementById("testeeId").SetAttribute("value", "");
			webBrowser1.Document.GetElementById("commentXml").SetAttribute("value", "<canvas/>"); //不确定，是否死值

			HTMLDocument htmlDocument = (HTMLDocument)webBrowser1.Document.DomDocument;
			HTMLFormElement htmlFormElementClass = (HTMLFormElement)htmlDocument.forms.item("confirmMarkForm");
			htmlFormElementClass.submit();
		}

		/// <summary>
		/// LOG
		/// </summary>
		private void LogMarkInfo(string submitFlag)
		{

			PartrailQuestionService partrailQuestionService = new PartrailQuestionService();

			List<RecordData> recordDatas = GetSubmitData(submitFlag);

			partrailQuestionService.SubmitMarkableQuestions(recordDatas);

		}

		bool _isFirstKeyDown = true;
		private void webBrowser1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
		{
			if (e.KeyCode == Keys.Space)
			{
				if (_isFirstKeyDown)
				{
					btnMarkConfirmed_Click(null, null);

				}
				_isFirstKeyDown = !_isFirstKeyDown;

			}
		}
	}
}
